package cn.com.twoke.easyproject.config.event;


import cn.com.twoke.easyproject.config.thread_pool.DealErrorThreadFactory;
import cn.com.twoke.easyproject.config.thread_pool.RequestContextTaskDecorator;
import cn.com.twoke.easyproject.config.thread_pool.UserLoginContextTaskDecorator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步事件线程池配置
 */
@Configuration
@Slf4j
@EnableAsync
public class EventThreadPoolConfiguration {

    public static final String EVENT_EXECUTOR = "EventExecutor";


    @Bean(EVENT_EXECUTOR)
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(
            UserLoginContextTaskDecorator userLoginContextTaskDecorator,
            RequestContextTaskDecorator requestContextTaskDecorator
    ) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(50);
        executor.setKeepAliveSeconds(30);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setTaskDecorator((runnable) ->
                // 用户登录上下文
                userLoginContextTaskDecorator.decorate(
                        // 请求上下文
                        requestContextTaskDecorator.decorate(runnable)
                )
        );
        executor.setThreadNamePrefix("EventExecutor-");
        executor.setThreadFactory(new DealErrorThreadFactory(executor));
        return executor;
    }


}
